package com.ruoze.bdp.function.impl;

import com.ruoze.bdp.constants.DataSourceConstants;
import com.ruoze.bdp.enums.DbType;
import com.ruoze.bdp.function.JDBCDataSourceFunction;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ClickHouseDataSourceFunction extends JDBCDataSourceFunction {
    @Override
    public String getDriverName() {
        return DataSourceConstants.COM_CLICKHOUSE_JDBC_DRIVER;
    }

    @Override
    public String getValidationQuery() {
        return DataSourceConstants.CLICKHOUSE_VALIDATION_QUERY;
    }

    @Override
    public String getMetaDatabasesQuery() {
        return DataSourceConstants.CLICKHOUSE_META_DATABASES_QUERY;
    }

    @Override
    public String getMetaDatabasesQueryColumn() {
        return DataSourceConstants.CLICKHOUSE_META_DATABASES_QUERY_COLUMN;
    }

    @Override
    public String getMetaTablesQuery(String database) {
        return String.format(DataSourceConstants.CLICKHOUSE_META_TABLES_QUERY, database);
    }

    @Override
    public String getMetaTablesQueryColumn() {
        return DataSourceConstants.CLICKHOUSE_META_TABLES_QUERY_COLUMN;
    }

    @Override
    public String getMetaColumnsQuery(String database, String table) {
        return String.format(DataSourceConstants.CLICKHOUSE_META_COLUMNS_QUERY, database, table);
    }

    @Override
    public String getCreateTableExecQuery(String name, List<Map<String, String>> columnDefinitionList, Map<String, Object> tableOptions) {
        StringBuilder create = new StringBuilder("create table if not exists ")
                .append(name).append("(");
        // 字段
        for (int i = 0; i < columnDefinitionList.size(); i++) {
            Map<String, String> definition = columnDefinitionList.get(i);
            create.append(definition.get("columnName")).append(" ").append(definition.get("columnType"));
            if (i != columnDefinitionList.size() - 1) {
                create.append(",");
            } else {
                create.append(")");
            }
        }
        // 其他
        tableOptions.forEach((key, value) -> {
            if (StringUtils.equalsAnyIgnoreCase(key, "engine")) {
                create.append(key).append("=").append(value).append(" ");
            } else {
                create.append(key).append(" ").append(value).append(" ");
            }
        });
        return create.toString();
    }

    @Override
    public DbType getSourceType() {
        return DbType.CLICKHOUSE;
    }
}
